library game;

import 'dart:html' as html;

/// A pausable game clock, measuring time in milliseconds.
class Clock {
  Date _last;
  int _elapsed = 0;
  bool _paused = false;
  
  Clock() : _last = new Date.now();
  
  int now() {
    if (_paused) {
      return _elapsed;
    }
    return _elapsed + (new Date.now().millisecondsSinceEpoch
        - _last.millisecondsSinceEpoch);
  }
  
  void pause() {
    _elapsed = now();
    _paused = true;
  }
  
  void resume() {
    _paused = false;
    _last = new Date.now();
  }
}

/**
 * A driver is what is currently running your game. You probably have one
 * driver for the main game, maybe another one for the combat system if it's
 * not fully integrated in the world (say, Final Fantasy style), another for
 * menus...
 */
abstract class Driver {
  final Clock clock;
  Driver() : clock = new Clock();
  Driver update();
  void render(html.CanvasRenderingContext2D ctx);
}

class Game {
  Driver defaultDriver;
  html.CanvasElement canvas;
  Driver _currentDriver;
  Set<int> keys;
  
  Game(this.canvas, this.defaultDriver) {
    _currentDriver = defaultDriver;
    keys = new Set<int>();
  }

  keyDown(html.KeyboardEvent k) {
    keys.add(k.keyCode);
    //print(k.keyCode);
  }

  keyUp(html.KeyboardEvent k) {
    keys.remove(k.keyCode);
  }
  
  run() {
    html.window.on.keyDown.add(keyDown);
    html.window.on.keyUp.add(keyUp);
    html.window.setInterval(_ratchet, (1000 ~/ 30).toInt());
  }
  
  _ratchet() {
    var nextDriver = _currentDriver.update();
    canvas.context2d.fillStyle = 'white';
    canvas.context2d.fillRect(0, 0, canvas.width, canvas.height);
    _currentDriver.render(canvas.context2d);
    _currentDriver = nextDriver;
    if (_currentDriver == null) {
      _currentDriver = defaultDriver;
    }
  }
}
